package com.lzx.iteam.adapter;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lzx.iteam.CRMContactActivity;
import com.lzx.iteam.CRMTextSelectActivity;
import com.lzx.iteam.R;
import com.lzx.iteam.bean.CRMCommentData;
import com.lzx.iteam.widget.gridimg.MyGridView;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.RoundImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;


/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 07月 29日
 * Time: 上午9:46
 *
 * @QQ : 1234567890
 * **********************************
 */
public class CRMContactAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<CRMCommentData> mListData;

    private EventImageAdapter mImageAdapter;
    private MediaPlayUtil mMediaPlayUtil;
    private AnimationDrawable mImageAnim;
    private ViewHolder mViewHolder;
    private int mPosition;
    private ArrayList<String> mImageOri;
    String[] mImageThumb;
    StringBuilder mImages;
    private String[] count = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};


    public CRMContactAdapter(Context mContext) {
        this.mContext = mContext;
        mMediaPlayUtil = MediaPlayUtil.getInstance();
    }

    public void bindData(ArrayList<CRMCommentData> data){
        this.mListData = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mListData == null ? 0:mListData.size();
    }

    @Override
    public Object getItem(int position) {
        return mListData == null ? null:mListData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        return mListData.get(position).getFlag();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final CRMCommentData data = mListData.get(position);
        CRMCommentData beforeData = null;
        if (position != 0){
            beforeData = mListData.get(position - 1);
        }
        ViewHolder holder = null;
        if (convertView == null){
            if (getItemViewType(position) == 0){
                convertView = LayoutInflater.from(mContext).inflate(R.layout.crm_contact_item1_layout,null);
                holder = new ViewHolder();
                holder.mTvOrigin = (TextView) convertView.findViewById(R.id.reply_tv_origin);
                holder.mTvName = (TextView) convertView.findViewById(R.id.reply_tv_name);
                holder.mIvAvtar = (RoundImageView) convertView.findViewById(R.id.reply_iv_avatar);
                holder.mTvComment = (TextView) convertView.findViewById(R.id.reply_tv_content);
                holder.mTvDuration = (TextView) convertView.findViewById(R.id.reply_tv_voice_len);
                holder.mGvImage = (MyGridView) convertView.findViewById(R.id.reply_image_layout);
                holder.mLayoutVoice = (LinearLayout) convertView.findViewById(R.id.reply_ll_voice);
                holder.mIvVoice = (ImageView) convertView.findViewById(R.id.reply_iv_voice_image);
                holder.mIvVoiceAnim = (ImageView) convertView.findViewById(R.id.reply_iv_voice_image_anim);

            }else{
                convertView = LayoutInflater.from(mContext).inflate(R.layout.crm_contact_item2_layout,null);
                holder = new ViewHolder();
                holder.mTvSystem = (TextView) convertView.findViewById(R.id.reply_tv_system);
            }
            holder.mTvTime = (TextView) convertView.findViewById(R.id.reply_tv_time);
            holder.month = (TextView) convertView.findViewById(R.id.crm_tv_month);
            holder.topLine = convertView.findViewById(R.id.crm_item_view_top);
            holder.bottomLine = convertView.findViewById(R.id.crm_item_view_bottom);
            convertView.setTag(holder);

        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        String time = data.getcTime();
        if (!StringUtil.isEmpty(time)){
            holder.mTvTime.setText(DateUtil.getUpDateTime(Long.parseLong(time) * 1000));
        }
        if (data.getFlag() == 0){ // 评论消息
            holder.mTvOrigin.setText("来自" + CRMTextSelectActivity.origin[data.getType()]);
            if (StringUtil.isEmpty(data.getUserImage())) {
                Log.d("data.getAvatar()", "  kong  de  ");
            } else {
                ImageLoaderInterface.imageLoader.displayImage(data.getUserImage(), holder.mIvAvtar, ImageLoaderInterface.optionHeadImage);
            }
            holder.mTvName.setText(data.getUserName());
            if (!StringUtil.isEmpty(data.getContent())){
                holder.mLayoutVoice.setVisibility(View.GONE);
                holder.mTvComment.setVisibility(View.VISIBLE);
                holder.mTvComment.setText(data.getContent());
                holder.mTvComment.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        ((CRMContactActivity) mContext).showCopyPop(view, data.getContent());
                        return false;
                    }
                });
            }else{
                holder.mTvComment.setVisibility(View.GONE);
            }

            if(data.getAttachments()!=null){
                try {
                    JSONArray attachments = new JSONArray(data.getAttachments());
                    mImageThumb = new String[attachments.length()];
                    mImageOri = new ArrayList<String>();
                    mImages = new StringBuilder();
                    for (int j = 0; j < attachments.length(); j++) {
                        JSONObject attachment = attachments.getJSONObject(j);
                        if ("1".equals(attachment.getString("type"))) {
                            holder.mGvImage.setVisibility(View.VISIBLE);
                            holder.mLayoutVoice.setVisibility(View.GONE);
                            mImageOri.add(attachment.getString("ori"));
                            mImageThumb[j] = attachment.getString("thumb");
                            mImages.append(attachment.getString("thumb")).append(",");
                        } else {
                            holder.mLayoutVoice.setVisibility(View.VISIBLE);
                            holder.mTvComment.setVisibility(View.GONE);
                            holder.mGvImage.setVisibility(View.GONE);

                            if (!StringUtil.isEmpty(attachment.getString("ori"))) {

                                holder.mTvDuration.setText(attachment.getString("duration") + '"');

                                // TODO 防止语音正在播放时，滑动发生布局复用时发生混乱
                                if (mMediaPlayUtil.isPlaying()) {
                                    if (mPosition != position) {
                                        holder.mIvVoice.setVisibility(View.VISIBLE);
                                        holder.mIvVoiceAnim.setVisibility(View.GONE);
                                    } else {
                                        holder.mIvVoice.setVisibility(View.GONE);
                                        holder.mIvVoiceAnim.setVisibility(View.VISIBLE);
                                    }
                                }

                                holder.mLayoutVoice.setOnClickListener(new AnimClick(holder, attachment.getString("ori"), position));

                            }
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String uid = PreferenceUtil.getInstance(mContext).getString(PreferenceUtil.CLIENT_USEID,"-1");
                if (!StringUtil.isEmpty(Constants.NEW_CRM_REPLY_TIME) && Constants.NEW_CRM_REPLY_TIME.equals(data.getcTime()) && uid.equals(data.getUserId())){
                    Log.d("crm_new_reply","  one int  here  " + Constants.NEW_CRM_REPLY_TIME + "  ====  " +data.getcTime());
                    mImageAdapter = new EventImageAdapter(mContext, mImageThumb, mImageOri, mImages.substring(0, mImages.length()), true);
                } else{
                    mImageAdapter = new EventImageAdapter(mContext, mImageThumb, mImageOri, mImages.substring(0, mImages.length()), "");
                }
                holder.mGvImage.setAdapter(mImageAdapter);
            }else{
                holder.mLayoutVoice.setVisibility(View.GONE);
            }

        }else{ // 系统消息
            holder.mTvSystem.setText(data.getContent());
        }

        int beforeMonth = 0;
        int month = DateUtil.getMonth(Long.parseLong(data.getcTime()) * 1000);
        if (beforeData == null) {
            holder.month.setVisibility(View.VISIBLE);
            holder.month.setText(count[month] + "月");
        } else{
            beforeMonth = DateUtil.getMonth(Long.parseLong(beforeData.getcTime()) * 1000);
            if (month != beforeMonth){
                holder.month.setVisibility(View.VISIBLE);
                holder.month.setText(count[month] + "月");
            }else{
                holder.month.setVisibility(View.GONE);
            }
        }

        if (position == mListData.size() - 1){
            holder.bottomLine.setVisibility(View.GONE);
        }else{
            holder.bottomLine.setVisibility(View.VISIBLE);
        }
        return convertView;
    }

    class AnimClick implements View.OnClickListener {

        private ViewHolder viewHolder;
        private String voiceData;
        private int position;

        public AnimClick(ViewHolder viewHolder, String voiceData, int position) {
            this.viewHolder = viewHolder;
            this.voiceData = voiceData;
            this.position = position;
        }

        @Override
        public void onClick(View view) {
            // TODO 判断是不是之前点击的那条语音
            if (position == mPosition) {
                if (mMediaPlayUtil.isPlaying()) {
                    mMediaPlayUtil.stop();
                    mImageAnim.stop();
                    viewHolder.mIvVoice.setVisibility(View.VISIBLE);
                    viewHolder.mIvVoiceAnim.setVisibility(View.GONE);
                } else {
                    startAnim(viewHolder);
                    mMediaPlayUtil.play(voiceData);
                }
            } else {
                if (mMediaPlayUtil.isPlaying()) {
                    mMediaPlayUtil.stop();
                    mImageAnim.stop();
                    // TODO 停止之前语音的动画
                    mViewHolder.mIvVoice.setVisibility(View.VISIBLE);
                    mViewHolder.mIvVoiceAnim.setVisibility(View.GONE);
                }
                startAnim(viewHolder);
                mMediaPlayUtil.play(voiceData);
            }
            mPosition = position;
            mViewHolder = viewHolder;

        }
    }

    /**
     * 语音播放效果
     *
     * @param viewHolder
     */

    public void startAnim(final ViewHolder viewHolder) {

        mImageAnim = (AnimationDrawable) viewHolder.mIvVoiceAnim.getBackground();
        viewHolder.mIvVoiceAnim.setVisibility(View.VISIBLE);
        viewHolder.mIvVoice.setVisibility(View.GONE);
        mImageAnim.start();
        mMediaPlayUtil.setPlayOnCompleteListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                viewHolder.mIvVoice.setVisibility(View.VISIBLE);
                viewHolder.mIvVoiceAnim.setVisibility(View.GONE);
            }
        });
    }

    class ViewHolder{
        RoundImageView mIvAvtar;
        TextView mTvOrigin,mTvName,mTvTime;
        TextView mTvComment,mTvDuration;
        ImageView mIvVoice,mIvVoiceAnim;
        MyGridView mGvImage;
        LinearLayout mLayoutVoice;

        TextView mTvSystem;

        TextView month;
        View topLine;
        View bottomLine;
    }

}
